﻿using MongoDB.Driver;
using MongoDB.Driver.Linq;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.Entities.RiskRatings;
using System.Linq;
using System.Threading.Tasks;

namespace Sustainalytics.ScreeningTool.Synchronization.Caches
{
    public class MeiNamesCache : DictionaryCache<int, string>
    {
        public string this[int id] => GetValueOrEmpty(id, string.Empty);
    }

    public class MeiNamesCacheLoader : ICacheLoader<MeiNamesCache>
    {
        private readonly MeiNamesCache cache;
        private readonly IMongoCollection<RiskRatingMaterialEsgIssue> collection;

        public MeiNamesCacheLoader(
            MeiNamesCache cache,
            IMongoCollection<RiskRatingMaterialEsgIssue> collection)
        {
            this.cache = cache;
            this.collection = collection;
        }

        public async Task LoadAsync(ClientFacingProduct clientFacingProduct)
        {
            var values = await collection.AsQueryable()
                .GroupBy(x => x.ExternalId)
                .Select(grp => new { grp.Key, grp.First().Name })
                .ToListAsync();

            var items = values.ToDictionary(x => x.Key, x => x.Name);

            cache.AddItems(items);
        }
    }
}